package com.mrogrape.notepad.activity.action;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.List;

import com.mrogrape.notepad.Notepad;
import com.mrogrape.notepad.activity.view.MainFrameView;
import com.mrogrape.notepad.common.ExitActionHandler;
import com.mrogrape.notepad.common.NotepadUtils;
import com.mrogrape.notepad.common.ViewUtils;
import com.mrogrape.notepad.data.ApplicationContext;
import com.mrogrape.notepad.data.ViewContext;
import com.mrogrape.notepad.resource.Settings;
import com.mrogrape.notepad.resource.Strings;
import com.mrogrape.notepad.ui.ClosableTabPanel;
import com.mrogrape.notepad.ui.editor.ContentType;
import com.mrogrape.notepad.ui.editor.TextEditor;
import com.mrogrape.notepad.ui.filechooser.NotepadFileChooser;
import com.mrogrape.notepad.ui.filechooser.OpenOptionPane;
import com.mrogrape.notepad.ui.filechooser.SaveOption;
import com.mrogrape.notepad.ui.filechooser.SaveOptionPane;

public class MainFrameAction extends MainFrameView {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	@Override
	public TextEditor createNewEditor(ContentType type) {

		TextEditor editor = new TextEditor(type, super.getTabbedPane());
		this.addNewTab(editor);

		this.setSelectedWorkPanel(editor);
		return editor;
	}

	@Override
	public TextEditor createNewEditor(File file) {

		if(!ApplicationContext.isFileContentTypeSupported(file)){
			return null;
		}

		// 如果文件已经打开则不再创建新的编辑器。
		List<TextEditor> editors = super.getAllTextEditors();
		for (TextEditor editor : editors) {

			if (file.equals(editor.getFile())) {

				this.setSelectedWorkPanel(editor);
				return editor;
			}
		}

		TextEditor editor = new TextEditor(file, super.getTabbedPane());
		this.addNewTab(editor);
		this.setSelectedWorkPanel(editor);

		return editor;
	}

	@Override
	public TextEditor createNewEditor(ContentType type, String title) {

		TextEditor editor = new TextEditor(type, title, super.getTabbedPane());
		this.addNewTab(editor);
		this.setSelectedWorkPanel(editor);

		return editor;
	}

	@Override
	public boolean checkTitleUseable(String title) {

		// 获取所有的编辑器
		List<TextEditor> editors = super.getAllTextEditors();

		// 遍历所有编辑器的Title
		for (int i = 0; i < editors.size(); i++) {

			String tabTitle = editors.get(i).getViewableTitle();

			// 如果Title已经存在
			if (tabTitle.equalsIgnoreCase(title)) {

				return false;
			}
		}
		return true;
	}

	@Override
	protected void thiswindowClosing(WindowEvent e) {

		this.exitAction();
	}

	@Override
	protected void openMntmActionPerformed(ActionEvent e) {

		this.openAction();
	}

	@Override
	protected void openBtnActionPerformed(ActionEvent e) {

		this.openAction();
	}

	@Override
	protected void saveMntmActionPerformed(ActionEvent arg0) {

		this.saveAction();
	}

	@Override
	protected void saveBtnActionPerformed(ActionEvent arg0) {

		this.saveAction();
	}

	@Override
	protected void exitMntmActionPerformed(ActionEvent arg0) {

		this.exitAction();
	}

	@Override
	protected void newMenuBtnActionPerformed(ActionEvent e) {

		TextEditor editor = this.createNewEditor(ContentType.PLAIN_TEXT);
		this.setSelectedWorkPanel(editor);
	}

	@Override
	protected void saveAllMntmActionPerformed(ActionEvent arg0) {

		List<TextEditor> editors = this.getAllTextEditors();
		for (TextEditor editor : editors) {

			this.saveTextEditorContent(editor);
		}
	}

	private void openAction() {

		OpenOptionPane accessory = ViewContext.getOpenOptionPane();

		File file = ViewContext.getFileChooser().showOpenSingleFileDialog(this, accessory, Strings.Label.OPEN_FILE, new File(Settings.getSettings().getLastChoicFilePath()), true, null, ApplicationContext.getSupportedContentType());

		TextEditor textEditor = null;
		if (file != null) {

			// 如果文件已经打开则不再创建新的编辑器。
			List<TextEditor> editors = super.getAllTextEditors();
			for (TextEditor editor : editors) {

				if (file.equals(editor.getFile())) {

					textEditor = editor;
					break;
				}
			}

			// 添加新的编辑器
			if (textEditor == null) {
				textEditor = new TextEditor(file, accessory.getCharset(), this.getTabbedPane());
				this.addNewTab(textEditor);
			}

			// 选中当前编辑器
			super.setSelectedWorkPanel(textEditor);

			Settings.getSettings().setLastChoicFilePath(file.getAbsolutePath());
			ViewContext.getRecentFileMenu().loadOrSaveFile(file);
		}
	}

	private void saveAction() {

		// 获取当前活动编辑器
		TextEditor editor = super.getCurrentTextEditor();

		// 如果不存在
		if (editor == null) {
			return;
		}

		this.saveTextEditorContent(editor);
	}

	/** 退出操作 */
	private void exitAction() {

		// 通知监听器
		for(ExitActionHandler eah : ApplicationContext.exitActionHandlers){
			if(!eah.onApplicationExit(this)){
				return;
			}
		}

		// 确认
		int re = ViewUtils.showOkCancelDialog(this, "Alert", "Are you sure you want to exit JNotepad?");

		if (re == ViewUtils.CANCEL_OPTION) {

			return;
		}

		// 关闭工作区中全部的编辑器。
		for (ClosableTabPanel panel : super.getAllWorkPanels()) {

			if (!panel.onClose()) {
				return;
			}
		}

		// 保存主窗体大小和状态
		if (this.getExtendedState() != Frame.MAXIMIZED_BOTH) {
			Settings.getSettings().setMainFrameSize(this.getSize());
		}
		Settings.getSettings().setMainFrameState(this.getExtendedState());



		Notepad.exit(0);
	}

	/**
	 * 保存一个文本编辑器的内容
	 * 
	 * @param editor
	 */
	private void saveTextEditorContent(TextEditor editor) {

		if (editor.getFile() == null) {

			SaveOption option = new SaveOption();
			option.setCharset(editor.getCharset());
			File optimisticFile = editor.getFile() == null ? NotepadUtils.createNearlyFilePath(new File(Settings.getSettings().getLastChoicFilePath()), editor.getPlainTitle()) : editor.getFile();

			SaveOptionPane accessory = ViewContext.getSaveOptionPane();
			accessory.setCharset(editor.getCharset());
			accessory.setSelectedLineSeparator(editor.getLineSeparator());

			NotepadFileChooser filechooser = ViewContext.getFileChooser();
			File file = filechooser.showSaveFileDialog(editor, accessory, null, optimisticFile, true, true, editor.getContentType(), ApplicationContext.getSupportedContentType());

			if (file != null) {
				editor.setFile(file, false);
				editor.setCharset(accessory.getCharset());
				editor.setLineSeparaotr(accessory.getSelectedLineSeparator());
				editor.saveFile();

				Settings.getSettings().setLastChoicFilePath(file.getAbsolutePath());
				ViewContext.getRecentFileMenu().loadOrSaveFile(file);
			}
		}
		else{
			editor.saveFile();
		}

	}



}
